package com.kgo.generation.database;

import cn.hutool.db.Entity;
import cn.hutool.db.SqlConnRunner;
import cn.hutool.db.SqlRunner;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.fastjson.JSON;
import com.kgo.generation.enums.DBDriver;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Kdb {
    private static SqlRunner sqlQuery = null;

    public static void initDBSource(String url, String userName, String password) {
        SimpleDataSource dbSource = new SimpleDataSource(url,userName,password);
        dbSource.setDriver(DBDriver.MYSQL.getValue());
        sqlQuery = SqlRunner.create(dbSource);
    }

    public  static void initDBSource(String url, String userName, String password, DBDriver dbDriver) {
        SimpleDataSource dbSource = new SimpleDataSource(url,userName,password);
        dbSource.setDriver(dbDriver.getValue());
        sqlQuery = SqlRunner.create(dbSource);
    }

    public static List<Entity> doSql(String sql, Object... params) {
        try {
            return sqlQuery.query(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> List<T> doSql(String sql,Class<T> beanClass, Object... params) {
        try {
            List<Entity> sqlList = sqlQuery.query(sql, params);
            List<T> result = new ArrayList<T>();
            for(int i = 0;i < sqlList.size();i++){
                result.add( JSON.parseObject(JSON.toJSONString(sqlList.get(i)),beanClass)) ;
            }
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static int add(Entity entity) {
        try {
            return sqlQuery.insert(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
